/* global qq */
import React, { useEffect, useState } from 'react'
import styles from '../index.module.less';

export default function Map(props) {
    const [map, setMap] = useState();
    const [overlay, setOverlay] = useState();
    useEffect(() => {
        initMap();
    }, []);
    useEffect(() => {
        if (props.overlayVisible && map) {
            addOverlay(map);
        } else {
            overlay && overlay.setVisible(false);
        }
    }, [props.overlayVisible]);
    useEffect(() => {
        if (props.earthVisible) {
            map && map.setMapTypeId(qq.maps.MapTypeId.SATELLITE);
        }
        else {
            map && map.setMapTypeId(qq.maps.MapTypeId.ROADMAP);
        }
    }, [props.earthVisible]);

    function addOverlay(map) {
        if (overlay) {
            overlay.setVisible(true);
            return;
        }
        const paths = props.coordinates.map(item => {
            return new qq.maps.LatLng(item[1], item[0]);
        });
        // console.log(paths);
        const polygon = new qq.maps.Polygon({
            path:paths,
            strokeColor: '#000000',
            strokeWeight: 5,
            fillColor: '#111111',
            map: map
        });
        // console.log(polygon);
        // map.addOverlay(polygon);
        setOverlay(polygon);
    }

    function initMap() {
        const map = new qq.maps.Map(document.getElementById('tmap'), {
            center: new qq.maps.LatLng(39.916527,116.397128),
            zoom: 8,
            // zoomControl: false,
            // panControl: false,
            mapTypeControl: false
        });
        setMap(map);
        props.overlayVisible && addOverlay(map);
    }
    return (
        <div id="tmap" className={styles.tmap}></div>
    )
}
